import {useContext, useMemo} from "react";
import {ResourceContext} from "@/app/lib/ResourceContext";

const resourceKey = 'resources'
const tokenKey = 'token'
const userKey = 'user'
const permissionKey = 'permissions'
const workKey = 'work'
const isBrowser = (typeof window !== "undefined");
export const loginUrl = '/login'
export const homeUrl = '/home'

export function clearStorage(){
  if(!isBrowser){
    return;
  }
  window.sessionStorage.clear();
  window.localStorage.clear();
}

export function setCurrentWork(work:string){
  if(!isBrowser){
    return;
  }
  window.sessionStorage.setItem(workKey,work)
}

export function getCurrentWork() {
  if(!isBrowser){
    return null;
  }
  return window.sessionStorage.getItem(workKey);
}

export function setToken(token:string){
  if(!isBrowser){
    return;
  }
  window.sessionStorage.setItem(tokenKey,token);
}

export function getToken(){
  if(!isBrowser){
    return null;
  }
  return window.sessionStorage.getItem(tokenKey);
}

export function persistToken(token:string){
  if(!isBrowser){
    return;
  }
  window.localStorage.setItem(tokenKey,token);
}
export function getPersistToken(){
  if(!isBrowser){
    return null;
  }
  return window.localStorage.getItem(tokenKey);
}

// @ts-ignore
export function Security({children,perm}){
  if(children == undefined){
    return <></>
  }
  if(perm == undefined){
    return children;
  }
  const resources = useContext(ResourceContext);
  if(resources == undefined
      || resources.permissions == undefined
      || resources.permissions.length == 0
      || resources.permissions.find(p => antPathMatcher(p.pattern,perm)) == undefined){
    return <></>
  }
  return children;
}


function antPathMatcher(pattern:string, path:string) {
  pattern = pattern.replace(/\./g, '\\.');
  pattern = pattern.replace(/\*/g, '.*');
  pattern = pattern.replace(/\\\*/g, '\\*');
  pattern = '^' + pattern + '$';
  
  const regex = new RegExp(pattern);
  return regex.test(path);
}